import os

from framework.Singleton import Singleton
from framework.syntacticSugar.EventEntiys import EventEntiys

errors_mod = []


class ModLoader(metaclass=Singleton):
    """
    将所有的mod进行加载
    """

    def __init__(self):
        print("[mod加载器-info] 开始运行")
        self.allmods = os.listdir("./mod")
        self.eventall = []
        """
        根据mod加载的所有的事件:
        [
            {"event": [xxx, xxx, xxx], "func": <func>}
        ]
        """



        self.authority = {}

        self.event_name = []
        self.event_effect_name = {}
        self.load()

    def load(self):
        """
        你只需要调用这个API就可以了
        :return:
        """
        self.__all_event()
        self.__all_auth()
        print("[mod加载器-info] " +
              (f"以下mods因为各种原因无法被加载，请检查mod版本和mod的代码问题:{'、'.join(errors_mod)}" if errors_mod != [] else "所有mod加载完全"))

    def __all_event(self):
        for modname in self.allmods:
            print(f"正在加载mod:{modname}事件...")
            path = "./mod/" + modname
            try:
                mod = __import__(f"mod.{modname}.active", globals(),
                                 locals(), ["event_bus"])
            except ModuleNotFoundError as e:
                print(f"[error] {modname} 不存在 事件模块")
                continue
            try:
                func = mod.event_bus
                ret: dict = func(EventEntiys())
                events_name = list(ret.keys())
                self.event_name += events_name

                the_event = {"events": events_name, "handler": func}
                print(f"[modloader] 加载到事件: {','.join(list(the_event.get('events')))}")

            except AttributeError as e:
                errors_mod.append(modname)
                print(f"[error] 警告 {modname}事件定义错误！\n\t错误提示{e}")
                raise e
                continue


            self.eventall.append(the_event)

    def __all_auth(self):
        for modname in self.allmods:
            if modname in errors_mod:
                print(f"[error] 由于事件未加载 {modname}权限加载失败")
                continue

            print(f"正在加载mod:{modname}权能...")
            path = "./mod/" + modname
            try:
                mod = __import__(f"mod.{modname}.auth", globals(),
                                 locals(), ["export"])
            except ModuleNotFoundError as e:
                print(f"{modname} 不存在 事件模块")
                return
            mod_auth = mod.export
            mod_auth = {k: i.replace("%/", f"mod.{modname}.") for k, i in mod_auth.items()}

            self.authority = dict(self.authority, **mod_auth)
